﻿/** book form operation add / edit * */
this.bookFormOperation = "add";

/** max row count * */
var MAX_ROW_COUNT = 14;// must be synced with PAGE_CAPACITY in Helper.java

/** shows new book panel * */
function showBookInfoPane() {
	showPopUp();
	$("#addBookInfoPane").css("visibility","visible");
	$("#addBookInfoPane").fadeIn("slow");
};

/** validate user info * */
function validateUserInfo() {
	var errorMsg = "الرجاء التأكد المعلومات التالية: \n";
	var isError = false;
	if ($("#name").val() == "") {
		errorMsg += "\tخانة الاسم يجب ان لا تكون فارغة\n";
		isError = true;
	}
	
	if($("#phone").val() == ""){
		errorMsg += "\tخانة رقم الهاتف يجب ان لا تكون فارغة \n";
		isError = true;
	}else if(isNaN($("#phone").val())){
			errorMsg += "\tخانة رقم الهاتف يجب ان تكون بالأرقام \n";
			isError = true;
		   }
	
	if ($("#address").val() == "") {
		errorMsg += "\tخانة عنوان المحل يجب ان لا تكون فارغة\n";
		isError = true;
	}
	if (isError) {
		alert(errorMsg);
		return false;
	}

	return true;
};

/** validate book info * */
function validateBookInfo() {
	var errorMsg = "الرجاء ادخال المعلومات التالية: \n";
	var isError = false;
	if ($("#bookName").val() == "") {
		errorMsg += "\tاسم الكتاب \n";
		isError = true;
	}

	if ($("#bookCollage").val() == "") {
		errorMsg += "\tاسم الكلية \n";
		isError = true;
	}

	if ($("#bookSubject").val() == "") {
		errorMsg += "\tموضوع الكتاب \n";
		isError = true;
	}

	if ($("#bookPrice").val() == "") {
		errorMsg += "\tسعر الكتاب \n";
		isError = true;
	} else if (isNaN($("#bookPrice").val())) {
		errorMsg += "\tسعر الكتاب بالأرقام \n";
		isError = true;
	}

	if (isError) {
		alert(errorMsg);
		return false;
	}

	return true;

}

/** selects tab * */
function selectTab(tabId) {
	// deselect current tab
	$("#top-navigation").find(".active").removeClass("active");
	// select the new
	$("#" + tabId + "").addClass("active");

	showBusyIndicator();
	$.get("/admin/body/" + tabId + "_page.jsp", "", function(data) {
		$("#center-column").html(data);
		hideBusyIndicator();
	});
}
 /** removes tab **/
function removeOtherTabs() {
/**	$("#" + tabId + "").remove();
	$("#top-navigation li").css("display:none");
	$("#userInfoTab").addClass("active");
**/
	$("#top-navigation li a").css("display","none");
	$("#userInfoTab").css("display","block").addClass("active");
}


/** close book info pane * */
function closeBookInfoPane() {
	$("#addBookInfoPane").fadeOut("fast");
	clearBookInfoFields();
//	closeBookInfoPane();
	hidePopUp();
};

/** clear book info pane fields * */
function clearBookInfoFields() {
	$("#addBookInfoPane input").each(function(index, src) {
		$(src).val("");
	});
}

/** edit book info * */
function editBookInfo(src) {
//	alert($(src).parent().parent().remove());
	this.bookFormOperation = "edit";
	var rowData = $(src).parent().parent().children().toArray();
	// fill edit book info fields:
	$("#bookName").val(jQuery.trim(rowData[0].innerHTML));
	$("#bookCollage").val(jQuery.trim(rowData[1].innerHTML));
	$("#bookSubject").val(jQuery.trim(rowData[2].innerHTML));
	$("#bookPrice").val(jQuery.trim(rowData[3].innerHTML));
	$("#id").val(jQuery.trim(rowData[4].innerHTML));
	$("#rowIndex").val(jQuery.trim(rowData[5].innerHTML));
	$dialog.dialog('open');
}

/** add new book * */
function addNewBook(requestString) {

	//setFormBusy();
	
	jQuery.ajaxSetup( {
		contentType : "application/json;charset=utf-8"
	});
	showBusyIndicator();
	$.get("/admin/addNewBook", requestString, function(data) {
		insertRow(data);
		setFormIdle();
		clearBookInfoFields();
		hideBusyIndicator();
//		hidePopUp();
	});
	hidePopUp();
	
}

/** deletes book * */
function deleteBook(src) {

	setFormBusy();
	
	var dialogResult = confirm("Are you sure you want to delete this book?");
	if(dialogResult){
		jQuery.ajaxSetup( {
			contentType : "application/json;charset=utf-8"
		});
		var rowData = $(src).parent().parent().children().toArray();
		var bookId = "id="+rowData[4].innerHTML+"&";
		var rowIndex = "rowIndex="+rowData[5].innerHTML;
		var reqString = bookId + rowIndex;
		
		showBusyIndicator();
		$.get("/admin/deleteBook", reqString, function(data) {
			if( data.result == "success"){
				removeRow(data.rowIndex);
				setFormIdle();
				updateRowIndexes();
			}
			hideBusyIndicator();

		});
	}
}

/** * */
function insertRow(rowData) {
	if (getRowCount() + 1 > MAX_ROW_COUNT) {
		removeLastRow();
	}
	$("#listingBody")
			.prepend(
					'<tr id="test"><td class="style2">'
							+ rowData.bookName
							+ ' </td>'
							+ '<td width="177" class="style2">'
							+ rowData.bookCollage
							+ '</td>'
							+ '<td width="177" class="style2">'
							+ rowData.bookSubject
							+ '</td>'
							+ '<td width="177" class="style2">'
							+ rowData.bookPrice
							+ '</td>'
							+ '<td style="display:none">'
							+ rowData.bookId
							+ '</td>'
							+ '<td style="display:none" class="rowIndex">'
							+ '&nbsp;'
							+ '</td>'
							+ '<td width="16" >'
							+ '<img src="img/hr.gif" width="16" height="16" alt="" onclick="deleteBook(this);" /></td>'
							+ '<td width="16" >'
							+ '<img class="editButton" onClick="editBookInfo(this);" src="img/edit-icon.gif" width="16" height="16" alt="edit"/></td>'
							+ '</tr>');
	updateRowIndexes();
}

/** edits given row **/
function editRowData(rowData) {
	var rowIndex = rowData.rowIndex;
	var targetRow = $("#listingBody tr:nth-child(" + rowIndex + ")").children();
	
	//edit table content:
	targetRow[0].innerHTML = rowData.bookName;
	targetRow[1].innerHTML = rowData.bookCollage;
	targetRow[2].innerHTML = rowData.bookSubject;
	targetRow[3].innerHTML = rowData.bookPrice;
	targetRow[4].innerHTML = rowData.bookId;
//	targetRow[5].innerHTML = rowData.rowIndex;
	
}

/** gets row count * */
function getRowCount() {
	return $("#listingBody tr").length;
}

/** removes row with given index* */
function removeRow(rowIndex) {
	$("#listingBody tr:nth-child(" + rowIndex + ")").remove();
}

/** removes last row * */
function removeLastRow() {
	$("#listingBody tr:last-child").remove();
}
/** clears book table from data **/
function clearBookTable() {
	$("#listingBody").children().remove();
}

/** init books info * */
function initBooks(data) {
	$(data).each(function(index, element) {
		insertRow(element);
	});
}

/** get specific page data **/
function getPageData(pageNumber) {
	showBusyIndicator();
	$.get("/admin/getAllBooks", "page="+pageNumber, function(data) {
		clearBookTable();
		var books = data.books;
		$(books).each(function(index, book){
			insertRow(book);
		});
		
		
		hideBusyIndicator();
	});
}
/** set from busy **/
function setFormBusy() {
	$("td div :submit").attr("disabled",true);
	$("td div :submit").text("جاري الحفظ...");
//	console.log("forms busy");
}

/** sets form idle **/
function setFormIdle() {
	$("td div :submit").attr("disabled",false);
	$("td div :submit").text("حفظ");
//	console.log("forms idle");
}

/** shows popup panel **/
function showPopUp() {
	var h = $("body").attr("offsetHeight");
	var w = $("body").attr("offsetWidth");
	if( h == 0){
		h = window.outerHeight;
		w = window.outerWidth;
	}
	var panel = "<div id='mask' style='z-index: 10;height: "+h+"px;width: "+w+"px; display: block; position: absolute; background-color: #000000;filter:alpha(opacity=25); opacity: 0.25;left: 0px; top: 0px;' >&nbsp;</div>"
	 
	$('body').prepend(panel);
//	$('#addBookInfoPane').wrap($('#mask'));
//	$('body').append('<div style="background-color: red; opacity: 1; position: relative; left: 35%; width: 400px; top: 200px; height: 200px; z-index: 300;"><button>asdf</button></div>');
//	$('body').append($("#addBookInfoPane"));
}

/** hides popup **/
function hidePopUp() {
	$("#mask").remove();
}


/** Book Form **/
function getBookPane(){
	var BookInfoPane = '';
	BookInfoPane += '<div id="addBookInfoPane">';
	BookInfoPane += '<form id="bookForm">';
	BookInfoPane += '<table class="listing form" cellpadding="0" cellspacing="0">';
	BookInfoPane += '	<tr>';
	BookInfoPane += '		<td width="172"><strong>اسم الكتاب</strong><span class="required">*</span></td>';
	BookInfoPane += '		<td><input id="bookName" name="bookName" type="text" class="text">';
	BookInfoPane += '		</input></td>';
	BookInfoPane += '	</tr>';
	BookInfoPane += '	<tr>';
	BookInfoPane += '		<td><strong>الكليّة</strong><span class="required">*</span></td>';
	BookInfoPane += '		<td><input id="bookCollage" name="bookCollage" type="text"';
	BookInfoPane += '			class="text" /></td>';
	BookInfoPane += '	</tr>';
	BookInfoPane += '	<tr>';
	BookInfoPane += '		<td><strong>المادّة</strong><span class="required">*</span></td>';
	BookInfoPane += '		<td><input id="bookSubject" name="bookSubject" type="text"';
	BookInfoPane += '			class="text" /></td>';
	BookInfoPane += '	</tr>';
	BookInfoPane += '	<tr>';
	BookInfoPane += '		<td><strong>السعر - شيكل</strong><span class="required">*</span></td>';
	BookInfoPane += '		<td><input id="bookPrice" name="bookPrice" type="text"';
	BookInfoPane += '			class="text" /> <input id="id" name="id" type="hidden">';
	BookInfoPane += '							<input id="rowIndex" name="rowIndex" class="rowIndex" type="hidden"></td>';
	BookInfoPane += '	</tr>';
	BookInfoPane += '</table>';
	BookInfoPane += '</form>';
	BookInfoPane += '</div>';

	return BookInfoPane;
};


/** book dialog **/
var $dialog = $('<div></div>').html(getBookPane()).dialog({
	modal: true,	
	width: 650, 
	height: 185, 
	autoOpen: false,
	title: 'اضافة كتاب جديد',
	buttons: {
				'add': function(){
							if( validateBookInfo()) {
								if( bookFormOperation == "add"){
									var formData = $("#bookForm").serialize();
									
									showBusyIndicator();
									$.get("/admin/addNewBook", formData, function(data) {
										insertRow(data);
										clearBookInfoFields();
										$dialog.dialog('close');
										hideBusyIndicator();
									});
								} else {
									var formData = $("#bookForm").serialize();
									
									showBusyIndicator();
									$.get("/admin/editBookInfo", formData, function(data) {
										editRowData(data);
										clearBookInfoFields();
										$dialog.dialog('close');
										hideBusyIndicator();
									});
								}

							}
							
						},
				'cancel': function(){$dialog.dialog('close');}
			}
		});


/** updates row indexes after update **/
function updateRowIndexes() {
	if($("td.rowIndex").length==0){
		$("#listingBody").append(getEmptyRow());
	}else{
		$("#emptyRow").remove();
		$("td.rowIndex").each(function(index, element){
			$(element).text(index + 1);
		});
	}
}

/** returns empty row **/
function getEmptyRow(){
	return "<tr><td id='emptyRow' class='style2' colspan='6' style='text-align:right; padding-right:10px'>لا يوجد كتب مضافة</td></tr>";
}

/** shows busy indicator **/
function showBusyIndicator(){
	var code = "";
	code += "<div id='busy' class='busy' top:0px'>";
	code += "<span>";
	code += "<img src='img/busy.gif'>";
	code += "يرجى الانتظار";
	code += "</span>";
	code += "</div>";
	$("body").prepend(code);
}

/** hides busy indicator **/
function hideBusyIndicator(){
	$('#busy').slideUp('slow');
	$('#busy').remove();
}